import type { ComputedRef } from "vue";
import type { DateModelType } from "element-plus";

interface Shortcut {
  text: string;
  value: () => [Date, Date];
}

const DAY = 24 * 60 * 60 * 1000;

const buildShortcut = (text: string, offsetStart: number, offsetEnd = 0) => ({
  text,
  value: () => {
    const end = new Date();
    end.setHours(23, 59, 59, 999);
    const start = new Date(end.getTime() - offsetStart * DAY);
    start.setHours(0, 0, 0, 0);
    if (offsetEnd) {
      end.setTime(end.getTime() - offsetEnd * DAY);
    }
    return [start, end] as [Date, Date];
  }
});

export const rangeShortcuts: Shortcut[] = [
  buildShortcut("最近7天", 6),
  buildShortcut("最近15天", 14),
  buildShortcut("最近30天", 29),
  buildShortcut("最近90天", 89)
];

export const singleShortcuts: Shortcut[] = [
  {
    text: "今天",
    value: () => {
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      const end = new Date();
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  },
  {
    text: "昨天",
    value: () => {
      const start = new Date(Date.now() - DAY);
      start.setHours(0, 0, 0, 0);
      const end = new Date(Date.now() - DAY);
      end.setHours(23, 59, 59, 999);
      return [start, end];
    }
  }
];

export const useDatePickerShortcuts = (): Shortcut[] => rangeShortcuts;

export const shortcuts = rangeShortcuts;

export const formatDateRange = (
  range: DateModelType,
  formatter: (date: Date) => string
): string[] => {
  if (!Array.isArray(range)) return [];
  return range.map(item => formatter(new Date(item as Date)));
};

export type DatePickerShortcuts = Shortcut[];
